<template>
  <nut-tabbar
    v-model="selected"
    class="tabbar-container"
    :style="{ paddingBottom: `${bottomDistance}px` }"
    size="18px"
    @tab-switch="handleClick"
  >
    <nut-tabbar-item
      :tab-title="item.title"
      :value="item.value"
      v-for="(item, index) in tabList"
      :key="index"
    >
      <template #icon="props">
        <img v-if="props.active" :src="item.activeImg" />
        <img v-else :src="item.img" />
      </template>
    </nut-tabbar-item>
  </nut-tabbar>
</template>
<script setup lang="ts">
import { storeToRefs } from "pinia";
import { reactive, onMounted } from "vue";
import { useTabbarStore } from "../../store";
import Taro, { eventCenter } from "@tarojs/taro";
const tabbarStore = useTabbarStore();
const { selected, bottomDistance } = storeToRefs(tabbarStore);
const router = Taro.useRouter();

type menu = {
  name: string;
  title: string;
  pagePath: string;
  img: any;
  activeImg: any;
  value: number;
};
const tabList = reactive([
  {
    name: "home",
    title: "首页",
    pagePath: "/pages/home/index",
    img: require("../../assets/icon/tabbar/2/3.png"),
    activeImg: require("../../assets/icon/tabbar/1/3.png"),
    value: 0,
  },
  {
    name: "cinema",
    title: "影院",
    pagePath: "/pages/cinema/index",
    img: require("../../assets/icon/tabbar/2/2.png"),
    activeImg: require("../../assets/icon/tabbar/1/2.png"),
    value: 0,
  },
  {
    name: "order",
    title: "订单",
    pagePath: "/pages/order/index",
    img: require("../../assets/icon/tabbar/2/5.png"),
    activeImg: require("../../assets/icon/tabbar/1/5.png"),
    value: 0,
  },
  {
    name: "my",
    title: "我的",
    pagePath: "/pages/my/index",
    img: require("../../assets/icon/tabbar/2/4.png"),
    activeImg: require("../../assets/icon/tabbar/1/4.png"),
    value: 0,
  },
]);
onMounted(() => {
  setBottomDistance();
  const url = tabList[selected.value].pagePath;
  handleToPath(url);
  eventCenter.once(router.onReady, () => {
    getTabbarHeight();
  });
});
const setBottomDistance = () => {
  const systemInfo = Taro.getSystemInfoSync();
  const safeArea: any = systemInfo.safeArea;
  const res = systemInfo.screenHeight - safeArea.bottom;
  tabbarStore.setBottomDistance(res);
};
const getTabbarHeight = () => {
  const query = Taro.createSelectorQuery()
    .select(".tabbar-container")
    .boundingClientRect();
  query.selectViewport();
  query.exec(function (res) {
    if (res[0]) {
      const height = res[0].height;
      tabbarStore.setTabbarHeight(height);
    }
  });
};

const handleClick = (item: any, index: number) => {
  console.log(item);
  
  let url = tabList[index].pagePath;
  handleToPath(url);
};
const handleToPath = (url) => {
  Taro?.switchTab({
    url: url,
  });
};
</script>
<style lang="less">
@import "./customTabBar.scss";
</style>
